package cn.bonoon.kernel.io.image;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import cn.bonoon.kernel.io.FileInfo;
import cn.bonoon.kernel.io.FileStoreHandler;
import cn.bonoon.util.ImageUtil;

/**
 * 对图片进行压缩处理
 * @author jackson
 *
 */
public class ImageCompression implements FileStoreHandler{
	
	private static List<String> images = Arrays.asList(".jpg", ".gif", ".png", ".bmp");

	public static ImageCompression compression = new ImageCompression();
	//最大的宽度不超过2048
	public static int IMAGE_MAX_WIDTH = 2048;
	private ImageCompression(){}
	
	@Override
	public FileInfo stored(FileInfo fileInfo) throws Exception {
		MultipartFile sourceFile = fileInfo.getSourceFile();
		File targetFile = fileInfo.getFile();
		
		if(isImage(fileInfo)){
			ImageUtil.zoom(sourceFile.getInputStream(), targetFile, sourceFile.getOriginalFilename().toLowerCase(), IMAGE_MAX_WIDTH);
		}else{
			sourceFile.transferTo(targetFile);
		}
		return fileInfo;
	}

	protected boolean isImage(FileInfo fileInfo){
		return images.contains(fileInfo.getFilesuffix());
	}
}
